import React, { useState, useEffect } from 'react'
import { Table, Button, notification } from 'antd'
import axios from 'axios'

export default function AuditList() {
  const [dataSource, setdataSource] = useState([])
  const {roleId,region,username}  = JSON.parse(localStorage.getItem("token"))

  useEffect(() => {
    getData()
  }, [])

  const getData = () => {
    const roleObj = {
        "1":"superadmin",
        "2":"admin",
        "3":"editor"
    }
    axios.get(`/news?auditState=1&_expand=category`).then(res => {
        const list = res.data
       setdataSource(roleObj[roleId]==="superadmin"?list:[
        ...list.filter(item=>item.author===username),
        ...list.filter(item=>item.region===region&& roleObj[item.roleId]==="editor")
    ])
    })
  }

  const passItem = (item, auditState, publishState) => {
    axios
      .patch(`/news/${item.id}`, {
        auditState,
        publishState,
      })
      .then((res) => {
        getData()
        notification.info({
          message: `通知`,
          description: `您可以到[审核管理/审核列表]中查看您的新闻的审核状态`,
          placement: 'bottomRight',
        })
      })
  }

  const columns = [
    {
      title: '新闻标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '作者',
      dataIndex: 'author',
      key: 'author',
    },
    {
      title: '新闻分类',
      key: 'categoryId',
      render: (item) => item.category.title,
    },
    {
      title: '作者',
      key: 'operate',
      render: (item) => {
        return (
          <div>
            <Button type="primary" onClick={() => passItem(item, 2, 1)}>
              通过
            </Button>
            <Button danger onClick={() => passItem(item, 3, 0)}>
              驳回
            </Button>
          </div>
        )
      },
    },
  ]
  return (
    <div>
      <Table
        columns={columns}
        dataSource={dataSource}
        pagination={{
          pageSize: 5,
        }}
      />
    </div>
  )
}
